
// Define SudokuUI object if it is not already defined
if (typeof SudokuUI === 'undefined') var SudokuUI = {};

SudokuUI.cookieMgt = 
{
	// Selected cookie item in case user wishes to delete any them.
	menuObj : null,

	// Convert all non-word characters to HTML entities
	stringToEntities : function (s)
	{
		return s.replace(/\W/g, function (s) { return '&#' + s.charCodeAt(0) + ';'; });
	},

	// Save a grid to cookie
	// Takes grid as argument, prompt user for name
	save : function (grid)
	{
		var value = grid.toString();
		if (value.match(/0{81}/))
		{
			alert('You cannot save an empty grid.');
			return;
		}

		var name = prompt('Please name your save.', '');
		if (name === null || name === '') return; // user entered empty string or cancelled

		var now = new Date();
		if (now.toLocaleString)
			value += '&' + now.toLocaleString();
		else 
			value += '&' + now.toString();

		yux.cookies.set(name, value, 356);
		SudokuUI.cookieMgt.render();
	},

	// Render cookie menu
	render : function ()
	{
		var AllCookies = yux.cookies.getAll();

		// console.log(document.cookie);
		if (!this.menuObj)
		{
			this.menuObj = new yux.SelectMenu('CookieGrids');
			this.menuObj.setPlaceholderText('No saved data');
		}

		this.menuObj.removeAll();

		for (var i = 0; i < AllCookies.length; i++)
		{
			// console.log('Cookie ' + i + ': '+ AllCookies[i].name + ': ' + AllCookies[i].content);
			var backref = AllCookies[i].content.match(/^(\d{81})&(.*)$/);
			// first backreference is the puzzle itself
			// second backreference is the date, used as tooltip
			if (backref)
			{
				var cluecount = backref[1].replace(/0*/g, '').length;
				
				var text = AllCookies[i].name +  ' (' + cluecount + ' clues)';
				var callback = this.generateCallback(backref[1]);
				this.menuObj.add(text, callback, {title : backref[2], cookieName : AllCookies[i].name});
			}
		}
	},

	generateCallback : function (fixed)
	{
		return function ()
		{
			SudokuUI.controller.loadPuzzle(fixed);
			document.getElementById('DeleteCookieButton').disabled = false;
		}
	},

	// Cookie menu operation - clear selection
	clearSelection : function ()
	{
		this.menuObj.clearSelection();
		document.getElementById('DeleteCookieButton').disabled = true;
	},

	// Cookie menu operation - delete selection
	deleteSelection : function ()
	{
		if (!this.menuObj.selectedIndex === -1)
		{
			alert('You must select a grid from the list.');
			return;
		}
		yux.cookies.del(this.menuObj.itemNodes[this.menuObj.selectedIndex].cookieName);

		SudokuUI.cookieMgt.render();
		document.getElementById('DeleteCookieButton').disabled = true;
	}
}
